package com.proposition.paper.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.proposition.commons.enums.CheckStatus;
import com.proposition.commons.enums.PaperPattern;
import com.proposition.commons.enums.PaperType;
import com.proposition.commons.model.*;
import com.proposition.paper.mapper.ExamCategoryMapper;
import com.proposition.paper.mapper.ExamClassMapper;
import com.proposition.paper.mapper.PaperExamMapper;
import com.proposition.paper.mapper.PaperMapper;
import com.proposition.paper.service.PaperService;
import com.proposition.support.security.CurrentUser;
import com.proposition.support.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 试卷逻辑处理
 *
 * @author 杨凯
 * @create 2017-11-06 10:39
 **/
@Slf4j
@Service
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements PaperService {

	@Autowired
	private PaperMapper paperMapper;
	@Autowired
	private PaperExamMapper paperExamMapper;
	@Autowired
	private ExamClassMapper examClassMapper;
	@Autowired
	private ExamCategoryMapper examCategoryMapper;


	@Override
	public List<String> selectYearList() {
		return paperMapper.selectYearList();
	}


	@Override
	public void checkPaper(String paperId, String checkStatus, String mark, boolean flag) {
		Paper paper = new Paper();
		paper.setId(paperId);
		paper.setRemark(mark);
		if (flag) {
			if (checkStatus.equals(CheckStatus.WEI_SHEN_HE.getDesc()) || checkStatus.equals(CheckStatus.YI_SHEN_UNPASS.getDesc())) {
				paper.setCheckUser1(CurrentUser.INSTANCE.getUserName());
				paper.setCheckStatus(CheckStatus.YI_SHEN_PASS);
			} else if (checkStatus.equals(CheckStatus.YI_SHEN_PASS.getDesc()) || checkStatus.equals(CheckStatus.ER_SHEN_UNPASS.getDesc())) {
				paper.setCheckUser2(CurrentUser.INSTANCE.getUserName());
				paper.setCheckStatus(CheckStatus.ER_SHEN_PASS);
			} else if (checkStatus.equals(CheckStatus.ER_SHEN_PASS.getDesc()) || checkStatus.equals(CheckStatus.SAN_SHEN_UNPASS.getDesc())) {
				paper.setCheckUser3(CurrentUser.INSTANCE.getUserName());
				paper.setCheckStatus(CheckStatus.SAN_SHEN_PASS);
			}
		} else {
			if (checkStatus.equals(CheckStatus.WEI_SHEN_HE.getDesc())) {
				paper.setCheckUser1(CurrentUser.INSTANCE.getUserName());
				paper.setCheckStatus(CheckStatus.YI_SHEN_UNPASS);
			} else if (checkStatus.equals(CheckStatus.YI_SHEN_PASS.getDesc())) {
				paper.setCheckUser2(CurrentUser.INSTANCE.getUserName());
				paper.setCheckStatus(CheckStatus.ER_SHEN_UNPASS);
			} else if (checkStatus.equals(CheckStatus.ER_SHEN_PASS.getDesc())) {
				paper.setCheckUser3(CurrentUser.INSTANCE.getUserName());
				paper.setCheckStatus(CheckStatus.SAN_SHEN_UNPASS);
			}
		}
		paperMapper.updateById(paper);

	}

	@Override
	public void revokePaper(String paperId, String checkStatus) {
		Paper paper = new Paper();
		paper.setId(paperId);
		if (checkStatus.equals(CheckStatus.YI_SHEN_PASS.getDesc()) || checkStatus.equals(CheckStatus.YI_SHEN_UNPASS.getDesc())) {
			paper.setCheckUser1(CurrentUser.INSTANCE.getUserName());
			paper.setCheckStatus(CheckStatus.WEI_SHEN_HE);
		} else if (checkStatus.equals(CheckStatus.ER_SHEN_PASS.getDesc()) || checkStatus.equals(CheckStatus.ER_SHEN_UNPASS.getDesc())) {
			paper.setCheckUser2(CurrentUser.INSTANCE.getUserName());
			paper.setCheckStatus(CheckStatus.YI_SHEN_PASS);
		} else if (checkStatus.equals(CheckStatus.SAN_SHEN_UNPASS.getDesc()) || checkStatus.equals(CheckStatus.SAN_SHEN_PASS.getDesc())) {
			paper.setCheckUser3(CurrentUser.INSTANCE.getUserName());
			paper.setCheckStatus(CheckStatus.ER_SHEN_PASS);
		}
		paperMapper.updateById(paper);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void paperAdd(PaperPattern pattern, PaperType paperType, String exam1, String exam2, String exam3) {
		int batch = generatePaperBatch(pattern, paperType);
		Paper paper = new Paper();
		String paperId = "";
		String paperName = "";
		String paperNumber = "";
		if (PaperPattern.WEN_DA == pattern) {
			paperId = UUIDUtil.getPaperUUID(PaperPattern.WEN_DA);
			paper.setPaperPattern(PaperPattern.WEN_DA);
			paper.setId(paperId);
			paperNumber = generatePaperNumber(pattern, paperType);
			paperName = "实践第一站" + paperNumber;
			paper.setNumber(paperNumber);
		} else if (PaperPattern.CHANG_GUI == pattern) {
			paperId = UUIDUtil.getPaperUUID(PaperPattern.CHANG_GUI);
			paper.setPaperPattern(PaperPattern.CHANG_GUI);
			paper.setId(paperId);
			paperNumber = generatePaperNumber(pattern, paperType);
			paperName = "实践第二站" + paperNumber;
			paper.setNumber(paperNumber);
		} else if (PaperPattern.KE_GUAN == pattern) {
			paperId = UUIDUtil.getPaperUUID(PaperPattern.KE_GUAN);
			paper.setPaperPattern(PaperPattern.KE_GUAN);
			paper.setId(paperId);
			paperNumber = generatePaperNumber(pattern, paperType);
			paperName = "实践第二站客观化" + paperNumber;
			paper.setNumber(paperNumber);
		} else {
			log.error("试卷分类错误");
		}
		if (PaperType.A == paperType) {
			paper.setType(PaperType.A);
		} else if (PaperType.B == paperType) {
			paper.setType(PaperType.B);
		} else {
			log.error("试卷类型错误");
		}
		paper.setName(paperName);
		paper.setBatch(batch);
		paper.setCheckStatus(CheckStatus.WEI_SHEN_HE);
		paper.setYear(Calendar.getInstance().get(Calendar.YEAR));
		paper.setUsername(CurrentUser.INSTANCE.getUserName());
		paper.setCreateTime(new Timestamp(System.currentTimeMillis()));
		paper.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		paperMapper.insert(paper);
		PaperExam paperExam = new PaperExam();
		paperExam.setPaperId(paperId);
		paperExam.setId(UUIDUtil.getUUID());
		paperExam.setExam1(exam1);
		paperExam.setExam2(exam2);
		paperExam.setExam3(exam3);
		paperExamMapper.insert(paperExam);
	}

	@Override
	public List<ExamClass> findExamClass() {
		return examClassMapper.selectList(new EntityWrapper<ExamClass>().orderBy("id"));
	}

	@Override
	public List<ExamCategory> findExamCategory(Integer id) {
		return examCategoryMapper.selectList(new EntityWrapper<ExamCategory>().eq("class_id", id));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deletePaper(String paperId) {
		Wrapper<PaperExam> wrapper = new EntityWrapper<>();
		wrapper.eq("paper_id", paperId);
		paperExamMapper.delete(wrapper);
		paperMapper.deleteById(paperId);
	}

	/**
	 * 需要根据试卷Id 判断试卷类型 判断试卷数据哪站
	 *
	 * @param paperId
	 * @return
	 */
	@Override
	public Map<String, Object> getPaperDetail(String paperId) {
		Map map = new HashMap<String, Object>(3);
		Paper paper = paperMapper.selectById(paperId);
		PaperExam paperExam = new PaperExam();
		paperExam.setPaperId(paperId);
		System.out.println(paperId);
		paperExam = paperExamMapper.selectOne(paperExam);
		String[] exam1 = paperExam.getExam1().split(",");
		String[] exam2 = paperExam.getExam2().split(",");
		String[] exam3 = paperExam.getExam3().split(",");
		switch (paper.getPaperPattern()) {
			//问答题
			case WEN_DA:
				//获取问答题腧穴题
				ExamAcupoint examAcupoint = new ExamAcupoint().selectOne(new EntityWrapper().eq("id", exam1[0]));
				map.put("exam1", "1、" + examAcupoint.getStem() + "。");
				map.put("exam1Score", examAcupoint.getTotalScore());
				ExamAnswer10 answer10 = new ExamAnswer10().selectOne(new EntityWrapper().eq("id", exam2[0]));
				map.put("exam2", "2、" + answer10.getStem() + "。");
				map.put("exam2Score", answer10.getTotalScore());
				answer10 = new ExamAnswer10().selectOne(new EntityWrapper().eq("id", exam3[0]));
				map.put("exam3", "3、" + answer10.getStem() + "。");
				map.put("exam3Score", answer10.getTotalScore());
				break;
			//常规化
			case CHANG_GUI:
			case KE_GUAN:
				StringBuilder sb = new StringBuilder();
				ExamAcupointAdult examAcupointAdult = null;
				ExamAcupointPediatric examAcupointPediatric = null;
				sb.append("<strong>一、穴位定位</strong>").append("<br/>");
				for (int i = 0; i < exam1.length; i++) {
					String category = exam1[i].substring(0, 2);
					if ("08".equals(category)) {
						examAcupointAdult = new ExamAcupointAdult().selectOne(new EntityWrapper().eq("id", exam1[i]));
						sb.append(examAcupointAdult.getStem())
								.append("、");
					} else if ("07".equals(category)) {
						examAcupointPediatric = new ExamAcupointPediatric().selectOne(new EntityWrapper().eq("id", exam1[i]));
						sb.append(examAcupointPediatric.getStem())
								.append("、");
					}

				}
				sb.deleteCharAt(sb.length() - 1).append("。");
				map.put("exam1", sb.toString());
				map.put("exam1Score", 10);
				//清空StringBuilder
				sb.setLength(0);
				ExamAnswer10 examAnswer10 = null;
				sb.append("<strong>二、单项手法</strong>")
						.append("<br/>");
				for (int i = 0; i < exam2.length; i++) {
					examAnswer10 = new ExamAnswer10().selectOne(new EntityWrapper().eq("id", exam2[i]));
					sb.append(i + 1)
							.append(".")
							.append(examAnswer10.getStem())
							.append("。")
							.append("<br/>");
				}
				map.put("exam2", sb.toString());
				map.put("exam2Score", 10);
				sb.setLength(0);
				ExamAnswer30 exam = new ExamAnswer30().selectOne(new EntityWrapper().eq("id", exam3[0]));
				sb.append("<strong>三、成套手法</strong>")
						.append("<br/>")
						.append(exam.getStem())
						.append("。");
				map.put("exam3", sb.toString());
				map.put("exam3Score", 10);
				break;
			default:
		}
		return map;
	}

	@Override
	public ExamCountForPaper getExamCount(int checkStatus) {
		ExamCountForPaper count = new ExamCountForPaper();
		if (checkStatus == -1) {
			Integer shuXue = new ExamAcupoint().selectCount(new EntityWrapper());
			Integer neiKeAnMo = new ExamAnswer10().selectCount(new EntityWrapper().eq("category_id", 2));
			Integer shangKeAnMo = new ExamAnswer10().selectCount(new EntityWrapper().eq("category_id", 3));
			Integer fuKeAnMo = new ExamAnswer10().selectCount(new EntityWrapper().eq("category_id", 4));
			Integer erKeTuiNa = new ExamAnswer10().selectCount(new EntityWrapper().eq("category_id", 5));
			Integer chuZhen = new ExamAnswer10().selectCount(new EntityWrapper().eq("category_id", 6));
			Integer chengRenXueWei = new ExamAcupointAdult().selectCount(new EntityWrapper());
			Integer keGuanHuaXueWei = new ExamAcupointAdult().selectCount(new EntityWrapper().where("category_id={0}", 16));
			Integer erKeXueWei = new ExamAcupointPediatric().selectCount(new EntityWrapper());
			Integer chengRenShouFa = new ExamAnswer10().selectCount(new EntityWrapper().eq("category_id", 10));
			Integer erKeShouFa = new ExamAnswer10().selectCount(new EntityWrapper().eq("category_id", 9));
			Integer chuZhenZhenDuan = new ExamAnswer10().selectCount(new EntityWrapper().eq("category_id", 11));
			Integer neiKeZhengTao = new ExamAnswer30().selectCount(new EntityWrapper().eq("category_id", 12));
			Integer shangKeZhengTao = new ExamAnswer30().selectCount(new EntityWrapper().eq("category_id", 13));
			Integer fuKeZhengTao = new ExamAnswer30().selectCount(new EntityWrapper().eq("category_id", 14));
			Integer erKeZhengTao = new ExamAnswer30().selectCount(new EntityWrapper().eq("category_id", 15));
			count.setXWCount(shuXue);
			count.setNKAMCount(neiKeAnMo);
			count.setSKAMCount(shangKeAnMo);
			count.setFKAMCount(fuKeAnMo);
			count.setEKTNCount(erKeTuiNa);
			count.setCRXWCount(chengRenXueWei);
			count.setKGHCount(keGuanHuaXueWei);
			count.setEKXWCount(erKeXueWei);
			count.setCRSFCount(chengRenShouFa);
			count.setEKSFCount(erKeShouFa);
			count.setNKZTCount(neiKeZhengTao);
			count.setSKZTCount(shangKeZhengTao);
			count.setFKZTCount(fuKeZhengTao);
			count.setEKZTCount(erKeZhengTao);
			count.setCZCount(chuZhen);
			count.setCZZDCount(chuZhenZhenDuan);
		} else {
			Integer shuXue = new ExamAcupoint().selectList(new EntityWrapper().setSqlSelect("DISTINCT mayor_cure1,mayor_cure2,mayor_cure3").eq("check_status_id", checkStatus)).size();
			Integer neiKeAnMo = new ExamAnswer10().selectList(new EntityWrapper().setSqlSelect("DISTINCT answer1,answer2,answer3").eq("category_id", 2).eq("check_status_id", checkStatus)).size();
			Integer shangKeAnMo = new ExamAnswer10().selectList(new EntityWrapper().setSqlSelect("DISTINCT answer1,answer2,answer3").eq("category_id", 3).eq("check_status_id", checkStatus)).size();
			Integer fuKeAnMo = new ExamAnswer10().selectList(new EntityWrapper().setSqlSelect("DISTINCT answer1,answer2,answer3").eq("category_id", 4).eq("check_status_id", checkStatus)).size();
			Integer erKeTuiNa = new ExamAnswer10().selectList(new EntityWrapper().setSqlSelect("DISTINCT answer1,answer2,answer3").eq("category_id", 5).eq("check_status_id", checkStatus)).size();
			Integer chuZhen = new ExamAnswer10().selectList(new EntityWrapper().setSqlSelect("DISTINCT answer1,answer2,answer3").eq("category_id", 6).eq("check_status_id", checkStatus)).size();
			Integer chengRenXueWei = new ExamAcupointAdult().selectList(new EntityWrapper().eq("check_status_id", 4)).size();
			Integer keGuanHuaXueWei = new ExamAcupointAdult().selectList(new EntityWrapper().where("category_id={0}", 16).eq("check_status_id", 4)).size();
			Integer erKeXueWei = new ExamAcupointPediatric().selectList(new EntityWrapper().eq("check_status_id", 4)).size();
			Integer chengRenShouFa = new ExamAnswer10().selectList(new EntityWrapper().setSqlSelect("DISTINCT answer1,answer2,answer3").eq("category_id", 10).eq("check_status_id", checkStatus)).size();
			Integer erKeShouFa = new ExamAnswer10().selectList(new EntityWrapper().setSqlSelect("DISTINCT answer1,answer2,answer3").eq("category_id", 9).eq("check_status_id", checkStatus)).size();
			Integer chuZhenZhenDuan = new ExamAnswer10().selectList(new EntityWrapper().setSqlSelect("DISTINCT answer1,answer2,answer3").eq("category_id", 11).eq("check_status_id", checkStatus)).size();
			Integer neiKeZhengTao = new ExamAnswer30().selectList(new EntityWrapper().eq("category_id", 12).eq("check_status_id", checkStatus)).size();
			Integer shangKeZhengTao = new ExamAnswer30().selectList(new EntityWrapper().eq("category_id", 13).eq("check_status_id", checkStatus)).size();
			Integer fuKeZhengTao = new ExamAnswer30().selectList(new EntityWrapper().eq("category_id", 14).eq("check_status_id", checkStatus)).size();
			Integer erKeZhengTao = new ExamAnswer30().selectList(new EntityWrapper().eq("category_id", 15).eq("check_status_id", checkStatus)).size();
			count.setXWCount(shuXue);
			count.setNKAMCount(neiKeAnMo);
			count.setSKAMCount(shangKeAnMo);
			count.setFKAMCount(fuKeAnMo);
			count.setEKTNCount(erKeTuiNa);
			count.setCRXWCount(chengRenXueWei);
			count.setKGHCount(keGuanHuaXueWei);
			count.setEKXWCount(erKeXueWei);
			count.setCRSFCount(chengRenShouFa);
			count.setEKSFCount(erKeShouFa);
			count.setNKZTCount(neiKeZhengTao);
			count.setSKZTCount(shangKeZhengTao);
			count.setFKZTCount(fuKeZhengTao);
			count.setEKZTCount(erKeZhengTao);
			count.setCZCount(chuZhen);
			count.setCZZDCount(chuZhenZhenDuan);
		}
		return count;
	}


	@Override
	public String generatePaperNumber(PaperPattern paperPattern, PaperType paperType) {
		String paperName = "";
		int year = Calendar.getInstance().get(Calendar.YEAR);
		int batch = generatePaperBatch(paperPattern, paperType);
		//根据站类型和试卷A/B 卷查询试卷已经组了多少套
		Wrapper wrapper = new EntityWrapper<Paper>();
		wrapper.eq("paper_pattern", paperPattern)
				.eq("type", paperType)
				.eq("year", year)
				.eq("batch", batch);
		int count = paperMapper.selectCount(wrapper);
		if (paperType == PaperType.A) {
			paperName = "A" + String.valueOf(count + 1);
		} else if (paperType == PaperType.B) {
			paperName = "B" + String.valueOf(count + 1);
		}
		return paperName;
	}

	/**
	 * 生成试卷批次
	 *
	 * @param pattern
	 * @param paperType
	 * @return
	 */
	public int generatePaperBatch(PaperPattern pattern, PaperType paperType) {
		int year = Calendar.getInstance().get(Calendar.YEAR);
		int batch;
		int count;
		//获取最新的批次
		Paper paper = paperMapper.selectBatch(pattern, paperType, year);

		Wrapper wrapper = new EntityWrapper<Paper>();
		wrapper.eq("paper_pattern", pattern)
				.eq("type", paperType)
				.eq("year", year);
		if (!ObjectUtils.isEmpty(paper)) {
			wrapper.eq("batch", paper.getBatch());
		}
		count = paperMapper.selectCount(wrapper);
		if (count == 0) {
			//如果本年度没有进行组卷，那么批次为1
			batch = 1;
		} else if (count == 20) {
			batch = paper.getBatch() + 1;
		} else {
			batch = paper.getBatch();
		}

		return batch;
	}

}
